import fs = require('fs');
import Qs = require('qs');
import path = require('path');
// 接口
interface ConfigJson {
	name: string;
	url: string;
	username: string;
	password: string;
}
export class Core {
	config: any;
	axios: any;
	constructor(config: ConfigJson,axios: any) {
		this.config = config;
		this.axios = axios;
	}
	// post请求
	async post(urlPath: string,data: any,headers: any) {
		return await this.axios({
			method: "POST",
			url: this.config.url + urlPath,
			data: data,
			headers
		});
	}
	// 登录
	login() {
		let data = {
			'orgName': this.config.name,
			'username' : this.config.username,
			'password' : this.md5(
				this.config.password
			)
		};
		this.post('system/jwtlogin',Qs.stringify(data,{encode:false}),{
				'Content-type' : 'application/x-www-form-urlencoded'
			}).then(res => {
			if(undefined == res.data.success) {
				console.log(res.data);
				console.log('登录失败');
				return false;
			}
			if(res.data.success == true) {
				console.log(res.data)
				console.log('登录成功');
				return false;
			}
			// 存入鉴权
			this.putAuthority(res.data.data,err =>{
				console.log(res.data);
				console.log('存入鉴权失败');
				return false;
			})
		})
		.catch(err => {
			// 登录失败 && 异常
			console.log(err);
		});
	}
	download(dict) {

		let Authority = this.getAuthority();
		let urlPath: string = 'maincheck/cdcUploadReport/download';
		return this.post(urlPath,Qs.stringify({
			code : dict // 字典代码
		}),{
			'Content-type' : 'application/x-www-form-urlencoded',
			'authorization' : Authority
		})
	}
	// 刷新token
	token() {
		let Authority = this.getAuthority();
		// 刷新
		this.post('system/refreshToken',Qs.stringify({}),{
			'Content-type' : 'application/x-www-form-urlencoded',
			'authorization' : Authority
		}).then(r => {
			if(r.data.success == true) {
				// 更新
				this.putAuthority(r.data.data,e=>{
					console.log(e)
				})
			}
		})
	}
	// 获取凭证
	getAuthority() {
		return fs.readFileSync(
			path.join(__dirname,'/../authorization.log')
		).toString();
	}
	// 添加凭证
	putAuthority(data: string,callback) {
		return fs.writeFile(path.join(__dirname,'/../authorization.log'), data, err=> {
			if (err) {
				callback(err);
			}
		})
	}
	// 计算md5
	md5(data: string) {
		return require('crypto')
		 .createHash('md5')
		 .update(data)
		 .digest('hex');
	}
}